﻿( function () {
  /* private vars. */

  /**
   * current user, get values after login.
   * levels同username/passcode一块存储，登录成功后读取上来,levels取值说明：
   * < 0 : 用于对应roles，处理特殊页面,user:-1;admin:-2;comba:-3;... 如：if(USER.isAuthorised(-1))；
   * = 0 : 默认值，数据库的param/struct的level值没有配置时的默认值;如果需要一个用户可访问默认权限的，levels添加0即可；
   * > 0 : 数据库param/struct的level值，webTips:||[param level]|[struct level]，表示levels包含该level值的用户可访问该param/struct；
   */
  var CUser = {
    name: "",
    passcode: "",
    levels: [-3, 0, 1, 3, 11, 13, 15, 16]
  }, AdminModules = {
    WASGuide: 0x0107, /* 工程级设置向导  */
    LogViewer: 0x271F, /* Log 显示功能 */
    Historydownload: 0x0709, /* 历史日志下载 */
    DisableLogCapacityLimit: 0x0219, /* 历史日志单次下载容量限制  */
    GSMHomeUpgrade: 0x0006, /* GSM Home升级路径 */
    VxWorks: 0x0006, /* VxWorks特殊 */
    GSMSpecial: 0x0007, /* GSM产品特殊 */
    zipLogsPath: 0x0110, /* Zip Log路径 */
    ONE_CARRIER: 0x0006, /* 家庭级设备只有一个载波 */
    XML_TREE: 0x271F,
    Help: 0x0007,

    /* 以下为无法归纳为功能点的产品线特殊处理  */
    LTE_EN: 0x0010,
    TD_HOME: 0x0500
  }, CombaModules = {
    WASGuide: 0x0107, /* 工程级设置向导  */
    LogViewer: 0x271F, /* Log 显示功能 */
    Historydownload: 0x0709, /* 历史日志下载 */
    DisableLogCapacityLimit: 0x0219, /* 历史日志单次下载容量限制  */
    GSMHomeUpgrade: 0x0006, /* GSM Home升级路径 */
    VxWorks: 0x0006, /* VxWorks特殊 */
    GSMSpecial: 0x0007, /* GSM产品特殊 */
    zipLogsPath: 0x0110, /* Zip Log路径 */
    ONE_CARRIER: 0x0006, /* 家庭级设备只有一个载波 */
    XML_TREE: 0x271F,
    wirelessCheck_v14_4: 0x0008, /* 2014.4版本无线诊断 */
    Help: 0x0007,

    /* 以下为无法归纳为功能点的产品线特殊处理  */
    LTE_EN: 0x0010,
    TD_HOME: 0x0500
  }, UserModules = {
    WASGuide: 0x0107, /* 工程级设置向导  */
    LogViewer: 0x271F, /* Log 显示功能 */
    Historydownload: 0x0709, /* 历史日志下载 */
    DisableLogCapacityLimit: 0x0219, /* 历史日志单次下载容量限制  */
    GSMHomeUpgrade: 0x0006, /* GSM Home升级路径 */
    VxWorks: 0x0006, /* VxWorks特殊 */
    GSMSpecial: 0x0007, /* GSM产品特殊 */
    zipLogsPath: 0x0110, /* Zip Log路径 */
    ONE_CARRIER: 0x0006, /* 家庭级设备只有一个载波 */
    XML_TREE: 0x271F,
    Help: 0x0007,

    /* 以下为无法归纳为功能点的产品线特殊处理  */
    LTE_EN: 0x0010,
    TD_HOME: 0x0500,
    DISABLE_SHOW:0x11 /*USER下某些参数灰色显示*/
  };

  /* public vars and interface */
  //用户角色定义，public
  Roles = {
    Market: "marketUser",
    Family: "familyUser",
    Root: "root"
  };
  /**
   * CProduct:Current Pruduct(当前产品线)，各产品线取值如下：
   * GSM_EN                  : 0x0001,
   * GSM_HOME                : 0x0002,
   * GSM_SINGLE_MODE         : 0x0004,
   * GSM_AU                  : 0x0008,
   *
   * LTE_EN                  : 0x0010,
   * GSM_BIG_VOLUME          : 0x0020,
   *
   * TD_HOME                 : 0x0100,
   * TD_AU                   : 0x0200,
   *
   * WCDMA_EN                : 0x1000,
   * 1588SERVICE             : 0x2000,
   */
  Branch = {
    CProduct: null,
    Modules: {
      notInit: true /* notInit用于配合初始化  */
    }
  };

  //有些功能有些产品线有有些没有
  Handle = {
    LogoComba: 0x0000 /*配置是否有logo和comba字样和版权*/
  }

  USER = {
    /**
     * 用于返回角色/显示名数组对，实现Home页面(user.asp也用)，对不同产品动态显示其所有的账户
     * @return{Array},format as: [["Role","show Name"],["Role","show Name"]]
     */
    getAccounts: function () {
      getProductType();
      var arr = [[Roles.Market, top.T.Home.MarketUser], [Roles.Root, top.T.Home.RootUser]];
      if (Branch.CProduct & UserModules.UserAccont) {
        arr.push([Roles.Family, top.T.Home.FamilyUser]);
      }
      return arr;
    },
    hasModule: function (module) {

      if (Branch.Modules.notInit) {
        getModules();
      }

      if (typeof (module) === "undefined") {
        return false;
      }

      if (Branch.CProduct & module) {
        return true;
      }
      return false;
    },
    login: function (account, passcode, role) {
      s
    },
    configLeftTreeTab: function () {
      /* 解决第一次调用USER.hasModule(module)时，module是undefined的问题，
       * 需确保第一次调用USER.hasModule(module)前调用  */
      if (Branch.Modules.notInit) {
        getModules();
      }

      /*注: 无法配置 基本信息 选项卡隐藏,基本信息选项卡是必选的 */
      $($("h3[name='baseInfoTree']")[0]).css("display", "none");

      if (USER.hasModule(Branch.Modules.XML_TREE)) {
        $($($("h3[name='baseInfoTree']")[0]).children()[0]).hide();
        $($($("h3[name='baseInfoTree']")[0]).children()[1]).hide();
      }
    },
    initTree: function () {
      CUser.levels = top.levels;
      setTimeout(loadDictionarys, 10);
    },

    /**
     * 传入一个level值，判断CUser.levels[]是否包含level,包含，返回true,否则，返回false.
     */
    isAuthorised: function (level) {
      try {
        var levelsStr = "", i = 0, len = CUser.levels.length;
        if (len === 0) {
          levelsStr = top.levels;
          CUser.levels = levelsStr.split(',');
          for (i = 0, len = CUser.levels.length; i < len; i += 1) {
            CUser.levels[i] = window.parseInt(CUser.levels[i], 10);
          }
        }

        if (CUser.levels.length === 0) {
          return false;
        }

        level = window.parseInt(level, 10);

        for (i = 0, len = CUser.levels.length; i < len; i += 1) {
          if (CUser.levels[i] === level) {
            return true;
          }
        }
        return false;
      } catch (e) {
        System.logout(1);
      }
    },

    /**
     * 通过localTree.StructLevels 取出struct or param 的level,
     * @params: s_p : 's'、'p',指示需要获取的level是struct level还是 param的level,
     * 没有相应level值时，返回  0
     */
    getStructLevel: function (StrLevels, s_p) {
      if (typeof (StrLevels) === "undefined") {
        alert("StrLevels undefined.");
      }
      var levels = StrLevels.split("|"), ret;

      if (s_p === "p") {
        if (levels.length < 3) {
          return 0;
        } else {
          ret = window.parseInt(levels[2], 10);
          return isNaN(ret) ? 0 : ret;
        }
      } else if (s_p === "s") {
        if (levels.length < 4) {
          return 0;
        } else {
          ret = window.parseInt(levels[3], 10);
          return isNaN(ret) ? 0 : ret;
        }
      } else {
        return 0;
      }
    }
  };

  /* private functions */
  function getProductType() {
    Branch.CProduct = 16;
  }

  function getModules(role) {
    getProductType();

    if (typeof (role) === "undefined") {
      role = top.role;
    }
    if (role === Roles.Market) {
      Branch.Modules = AdminModules;
    }
    else if (role === Roles.Root) {
      Branch.Modules = CombaModules;
    }
    else if (role === Roles.Family) {
      Branch.Modules = UserModules;
    }

    //设置G_PRODUCT_TYPE
    switch (Branch.CProduct) {
      case 0x0001:
        G_PRODUCT_TYPE = "GSM_EN";
        break;
      case 0x0002:
        G_PRODUCT_TYPE = "GSM_HOME";
        break;
      case 0x0004:
        G_PRODUCT_TYPE = "GSM_SINGLE_MODE";
        break;
      case 0x0008:
        G_PRODUCT_TYPE = "GSM_AU";
        break;

      case 0x0010:
        G_PRODUCT_TYPE = "LTE_EN";
        break;

      case 0x0100:
        G_PRODUCT_TYPE = "TD_HOME";
        break;
      case 0x0200:
        G_PRODUCT_TYPE = "TD_AU";
        break;

      case 0x1000:
        G_PRODUCT_TYPE = "WCDMA_EN";
        break;

      case 0x2000:
        G_PRODUCT_TYPE = "ONE_FIVE_EIGHT_EIGHT_SERVER"
        break;
    }
  }

  function loadDictionarys() {
    LMT.cmdSyn("get MetaData;", load_dictionary_callback);
    /*异步加载c_param表*/
  }

  var load_dictionary_cnt = 0;

  function load_dictionary_callback(dictionary) {
    var ackObj = -1, colNames = [];
    if (dictionary != "connect fail.") {
      load_alarm_dictionary_syn();
      /*等到结构体描述表加载完毕后再加载告警表,异步加载*/
      ackObj = LMT.parser(dictionary);
    }

    if (ackObj === -1 || ackObj.name_val.length === 0) {
      if (load_dictionary_cnt < 20) {
        load_dictionary_cnt += 1;
        setTimeout(loadDictionarys, 2000);
        Modal.progress("Loading...");
      } else {
        Modal.delProgress();
        initTrees([]);
      }
      return;
    }
    //else load db success

    Modal.delProgress();
    load_dictionary_cnt = 0;

    //获取数据库列名
    var fst_name = ackObj.name_val[0].name, cnt = 1, t_n = "", len = 0;
    colNames.push(fst_name);
    for (cnt = 1, len = ackObj.name_val.length; cnt < len; cnt += 1) {
      t_n = ackObj.name_val[cnt].name;
      if (fst_name !== t_n) {
        if (t_n === 'webTips' || t_n === 'WebTips') {//兼容老数据库
          t_n = "Level";
        }
        colNames.push(t_n);
      } else {
        break;
      }
    }

    localDB.DeleteTable("c_param");
    localDB.CreateTable("c_param", colNames);

    var vArr = [], i = 0;

    for (i = 0, len = ackObj.name_val.length; i < len; i += 1) {
      vArr.push(ackObj.name_val[i].val);
    }

    localDB.T_import("c_param", vArr);

    //计算列索引
    top.c_paramRowIndex = {
      StructID: localDB.T_getIndexByName("c_param", "StructID"),
      MemberID: localDB.T_getIndexByName("c_param", "MemberID"),
      StructName: localDB.T_getIndexByName("c_param", "StructName"),
      MemberName: localDB.T_getIndexByName("c_param", "MemberName"),
      IsPrimaryKey: localDB.T_getIndexByName("c_param", "IsPrimaryKey"),
      DefaultValue: localDB.T_getIndexByName("c_param", "DefaultValue"),
      Regex: localDB.T_getIndexByName("c_param", "Regex"),
      StructCnName: localDB.T_getIndexByName("c_param", "StructCnName"),
      MemberCnName: localDB.T_getIndexByName("c_param", "MemberCnName"),
      ClassifyName: 0,
      WebType: localDB.T_getIndexByName("c_param", "WebType"),
      TypeDesc: localDB.T_getIndexByName("c_param", "TypeDesc"),
      ValueType: localDB.T_getIndexByName("c_param", "ValueType"),
      Level: localDB.T_getIndexByName("c_param", "Level"),
      SetStatus: localDB.T_getIndexByName("c_param", "SetStatus")
      // Level字段是兼容老数据库的，现在的webTips字段就是Level.
    };

    /* 初始化各棵配置树 */
    if (Language === "EN") {
      localDB.emptyCol('c_param', 'MemberCnName');
    }

    localTree = LocalTree.init();
    initTrees(localTree);
  }

  function load_alarm_dictionary_syn() {
    LMT.cmdSyn("get AlarmDictionary;", load_alarm_dictionary_callback);
  }

  function load_alarm_dictionary_callback(dictionary) {
    var ackObj = LMT.parser(dictionary), colNames = [];

    if (ackObj.result === "000") {
      if (ackObj.name_val.length === 0) {
        colNames = ["ID", "AlarmIdentifier", "Name", "CnName", "Source", "PerceivedSeverity", "ProbableCause", "Condition", "Specification"];
        localDB.DeleteTable("alarm_dictionary");
        localDB.CreateTable("alarm_dictionary", colNames);
        return;
      }

      //获取所有列名
      var fst_name = ackObj.name_val[0].name, cnt = 1, len = 0, t_n = "";
      colNames.push(fst_name);
      for (cnt = 1, len = ackObj.name_val.length; cnt < len; cnt += 1) {
        t_n = ackObj.name_val[cnt].name;
        if (fst_name !== t_n) {
          colNames.push(t_n);
        } else {
          break;
        }
      }
      localDB.DeleteTable("alarm_dictionary");
      localDB.CreateTable("alarm_dictionary", colNames);

      var vArr = [];
      for (cnt = 0, len = ackObj.name_val.length; cnt < len; cnt += 1) {
        vArr.push(ackObj.name_val[cnt].val);
      }

      localDB.T_import("alarm_dictionary", vArr);
    } else {
      return;
    }
  }

  function initTrees(localTree) {
    if (USER.hasModule(Branch.Modules.XML_TREE)) {
      var footerIndex = 0;

      if (localTree.length === 0 && (USER.isAuthorised(-2) || USER.isAuthorised(-3))) {
        baseInfoTreeObj.ADD(baseInfoTreeObj.rootID, footerIndex.toString(), '0', '', Path.gotoLog, '', top.T.Tree.LogManagement, '4');
        footerIndex += 1;

        alert(top.T.Main.ErroNotice);
        baseInfoTreeObj.ON_OFF("1.0");
        return;
      }

      if (USER.hasModule(Branch.Modules.WLANParams)) {
        footerIndex = 0;
        baseInfoTreeObj.ADD(baseInfoTreeObj.rootID, footerIndex.toString(), '', '', AutoParamConfig.gotoWLANGuide, '', top.T.Tree.Guide, top.T.Tree.Guide);
        footerIndex += 1;

        baseInfoTreeObj.ADD(baseInfoTreeObj.rootID, footerIndex.toString(), '', '', AutoParamConfig.gotoDeviceInfo, '', top.T.Tree.DeviceState, top.T.Tree.DeviceState);
        footerIndex += 1;
      }

      //XML 配置的目录树
      var manObj = new ManTree("/manTree.xml?r=" + top.VALIDATION_STRING), i = 0, fNode = -1;
      manObj.initTree(baseInfoTreeObj);

      // 数据库配置的目录树
      var j = 0, len = 0, nodeName = "", nodeLevel = "", isExist = -1;
      for (i = 0; i < localTree.length; i += 1) {
        fNode = baseInfoTreeObj.FIND_NODE_BY_NAME(localTree[i].CN_class, baseInfoTreeObj.root);
        if (fNode == -1) {
          fNode = baseInfoTreeObj.FIND_NODE_BY_NAME(localTree[i].EN_class, baseInfoTreeObj.root);
        }

        if (fNode != -1) {
          footerIndex = baseInfoTreeObj.getMaxId(fNode) + 1;
          j = 0;
          for (j = 0, len = localTree[i].branche.length; j < len; j += 1) {
            if (Language === "EN") {
              nodeName = localTree[i].branche[j].structName;
            } else {
              nodeName = localTree[i].branche[j].StructCnName == "" ? localTree[i].branche[j].structName : localTree[i].branche[j].StructCnName;
            }
            nodeLevel = USER.getStructLevel(localTree[i].branche[j].StructLevels, "s");
            //获取结构体level,如果数据库中没有配,那么返回0

            isExist = baseInfoTreeObj.FIND_NODE_BY_NAME(nodeName, fNode);
            if (isExist != -1) {
              continue;
            }

            if (USER.isAuthorised(nodeLevel)) {
              if (localTree[i].branche[j].HasPrimarryKey == 1) {
                baseInfoTreeObj.ADD_BanUnique(fNode.nodeId, footerIndex.toString(), '', '', Path.showMulLeaf, '', nodeName, localTree[i].branche[j].structID + '@' + localTree[i].branche[j].structName);
              } else {
                // baseInfoTreeObj.ADD_BanUnique(fNode.nodeId, footerIndex.toString(), '', '', Path.showLeaf, '', nodeName, localTree[i].branche[j].structID + '@' + localTree[i].branche[j].structName);
              }
              footerIndex += 1;
            }
          }
        }
      }

      if (!USER.hasModule(Branch.Modules.WLANParams)) {//GSM单模的admin账号默认不打开第一层参数目录
        baseInfoTreeObj.OPEN_FST_LEVEL();
      }

      baseInfoTreeObj.SHOW();

      if (USER.hasModule(Branch.Modules.ONE_FIVE_EIGHT_EIGHT_SERVER)) {
        baseInfoTreeObj.ON_OFF("1.0.1");
      } else {
        if (!USER.hasModule(Branch.Modules.WLANParams)) {
          baseInfoTreeObj.ON_OFF("1.0.0");
          analyseURL();
        } else {
          baseInfoTreeObj.ON_OFF("1.1");
          analyseURL();
        }
      }
    }
  }

  /**
   * 用户级使用，配合参数自配置,定位子页面
   */
  function analyseURL() {
    var hash = window.location.hash;
    if (hash === "#index") {
      LMT.cmdSyn("get LAN;", function (data) {
        if (LMT.isCmdSuccess(data)) {
          var ret = LMT.parser(data), //
            vals = top.Struct.getValuesByMemberName(ret, ["GuideEnable"]);

          if (vals[0] === "1") {
            AutoParamConfig.gotoWLANGuide();
          }
        }
      });
    } else if (hash === "#wait") {
      AutoParamConfig.gotoAutoParamsConfig();
    }
  }

}());

/**
 *  导航树预处理,localTree生成
 */
var LocalTree = ( function () {
  function structIsVisiable(structsIDs, StructLevels, i) {
    switch (window.parseInt(StructLevels[i], 10)) {
      case 1:
        return true;
      case 2:
        return true;
      case 3:
        return true;
      case 4:
        return false;
      default:
        break;
    }
    return true;
  }

  function getAllstructs() {
    var structsIDs = localDB.T_getColumn("c_param", "StructID"), //
      structsNames = localDB.T_getColumn("c_param", "StructName"), //
      IsPrimaryKeys = localDB.T_getColumn("c_param", "IsPrimaryKey"), //
      StructCnNames = localDB.T_getColumn("c_param", "StructCnName"), //
      StructLevels = localDB.T_getColumn("c_param", "Level"), //
      WebTypes = localDB.T_getColumn("c_param", "WebType"), //
      ClassifyNames = localDB.T_getColumn("c_param", "ClassifyName"), //
      treeMeta = [], structID = "###", i = 0, len = 0, //
      o = {}, t_structID = "";

    for (i = 0, len = structsIDs.length; i < len; i += 1) {
      o = {};

      if (structsIDs[i] === "0" || structsIDs[i].length < 3) {
        continue;
      }

      if (window.parseInt(WebTypes[i], 10) === -2) {
        t_structID = structsIDs[i];
        while (t_structID === structsIDs[i]) {
          i += 1;
        }
        i -= 1;
        continue;
      }

      if (!structIsVisiable(structsIDs, StructLevels, i)) {
        continue;
      }

      if (structID === structsIDs[i]) {
        if (IsPrimaryKeys[i] == 1) {
          treeMeta[treeMeta.length - 1].HasPrimarryKey = 1;
        }
        continue;
      } else {
        if (IsPrimaryKeys[i] == 1) {
          o.HasPrimarryKey = 1;
        } else {
          o.HasPrimarryKey = 0;
        }
      }

      structID = structsIDs[i];
      o.structID = structsIDs[i];
      o.structName = structsNames[i];
      o.StructCnName = StructCnNames[i];
      o.StructLevels = StructLevels[i];
      o.Classify = ClassifyNames[i];

      treeMeta.push(o);
    }

    return treeMeta;
  }

  function createTreeNode() {
    var o = {};
    o.type = -1;
    o.CN_class = "";
    o.EN_class = "";
    o.branche = [];
    return o;
  }

  function createSubTreeNode() {
    var o = {};
    o.subType = -1;
    o.cnName = '';
    o.enName = '';
    o.structID = '';
    o.structName = '';
    o.leaf = [];
    return o;
  }

  function classify_structs(treeMeta) {
    var treeRoot = [], indexType = -1, //
      i = 0, len = 0, t_indexType = "", b_obj = {}, node = {}, //
      CNName = "", ENName = "", //
      j = 0, found = false, treeRootLen = 0;

    for (i = 0, len = treeMeta.length; i < len; i += 1) {
      t_indexType = treeMeta[i].Classify;

      if (treeRoot.length === 0) {
        b_obj = createTreeNode();
        node = createSubTreeNode();

        node.structID = treeMeta[i].structID;
        node.structName = treeMeta[i].structName;
        node.HasPrimarryKey = treeMeta[i].HasPrimarryKey;
        node.StructCnName = treeMeta[i].StructCnName;
        node.StructLevels = treeMeta[i].StructLevels;
        node.Classify = t_indexType;

        CNName = node.Classify.split("|")[0];
        ENName = node.Classify.split("|")[1];

        node.cnName = (CNName === "") ? t_indexType : CNName;
        node.enName = (ENName === "") ? t_indexType : ENName;

        b_obj.type = t_indexType;
        b_obj.CN_class = node.cnName;
        b_obj.EN_class = node.enName;

        b_obj.branche.push(node);

        treeRoot.push(b_obj);
      } else {
        for (j = 0, treeRootLen = treeRoot.length, found = false; j < treeRootLen; j += 1) {
          if (treeRoot[j].type === t_indexType) {
            node = createSubTreeNode();
            node.structID = treeMeta[i].structID;
            node.structName = treeMeta[i].structName;
            node.HasPrimarryKey = treeMeta[i].HasPrimarryKey;
            node.StructCnName = treeMeta[i].StructCnName;
            node.StructLevels = treeMeta[i].StructLevels;
            node.Classify = t_indexType;

            CNName = node.Classify.split("|")[0];
            ENName = node.Classify.split("|")[1];
            node.cnName = (CNName === "") ? t_indexType : CNName;
            node.enName = (ENName === "") ? t_indexType : ENName;

            treeRoot[j].branche.push(node);
            found = true;
            break;
          }
        }

        if (!found) {
          b_obj = createTreeNode();
          node = createSubTreeNode();

          node.structID = treeMeta[i].structID;
          node.structName = treeMeta[i].structName;
          node.HasPrimarryKey = treeMeta[i].HasPrimarryKey;
          node.StructCnName = treeMeta[i].StructCnName;
          node.StructLevels = treeMeta[i].StructLevels;
          node.Classify = t_indexType;

          CNName = node.Classify.split("|")[0];
          ENName = node.Classify.split("|")[1];
          node.cnName = (CNName === "") ? t_indexType : CNName;
          node.enName = (ENName === "") ? t_indexType : ENName;

          b_obj.type = t_indexType;
          b_obj.CN_class = node.cnName;
          b_obj.EN_class = node.enName;
          b_obj.branche.push(node);
          treeRoot.push(b_obj);
        }
      }
    }
    return treeRoot;
  }

  /**
   * return localTree
   */
  function init() {
    var treeMeta = getAllstructs();
    return classify_structs(treeMeta);
  }

  return {
    init: init
  };
}());
